from datetime import datetime

from fastapi import APIRouter, UploadFile, Depends, status, HTTPException
from sqlalchemy.orm import Session
from app.backend.db_depends import get_db
from typing import Annotated
from app.models import *
from sqlalchemy import insert, select, delete
from PIL import Image
import os

router = APIRouter(prefix='/documents', tags=['documents'])

@router.post('/upload_doc',
             description='Uploading images with text to the database and to disk',
             summary='Uploading a document')
def upload_document(file: UploadFile, db: Annotated[Session, Depends(get_db)]) -> dict:
    # if not os.path.isdir('./documents'):
    #     os.mkdir(fr'.app/documents')
    path = fr'../documents/{file.filename}'

    db.execute(insert(Documents).values(path=path, date=datetime.now()))
    with Image.open(file.file) as img:
        img.save(path)
    db.commit()
    return {
        'status_code': status.HTTP_200_OK,
        'transaction': 'The document has been added to the database and to the disk'
    }

@router.delete('/doc_delete',
               description='Deleting an image with text from the database and from the disk',
               summary='Deleting a document')
def delete_document(document_id: int, db: Annotated[Session, Depends(get_db)]) -> dict:
    document_delete = db.scalar(select(Documents).where(Documents.id == document_id))
    if document_delete is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail='There is no such document'
        )

    os.remove(document_delete.path)
    db.execute(delete(Documents).where(Documents.id == document_id))
    db.commit()

    return {
        'status_code': status.HTTP_200_OK,
        'transaction': 'The document was deleted from the database and disk'
    }

#docker exec -it postgres_app psql -U yourUser postgres